var moment = require('moment');
module.exports = {
  index: function (req, res) {
    console.log(req.session);
    res.view('user');
  },
  //加入购物车，post方法，参数：productId，amount，返回状态，加入商品信息
  addToCart: function (req, res) {
    var productId = req.body.productId;
    var amount = Number(req.body.amount);
    var openId = req.session.openId;

    Cart.findOrCreate({openId: openId, productId: productId}).then(function (result) {
      console.log(result);
      Cart.update({openId: openId, productId: productId}, {amount: result.amount+amount}).then(function (updated) {
        console.log(updated);
        res.send({status: 'success', data: updated});
      }).catch(function (err) {
        res.serverError(err);
      })
    }).catch(function (err) {
      res.serverError(err);
    })

  },

  cart: function (req, res) {
    var openId = req.session.openId;
    var products = [];
    Cart.find({openId: openId}).then(function (results) {
      console.log(results);
      var productInfo = [];
      var Promise = require('promise');
      // var i = 0;
      // for (r in results) {
      //   console.log(r);
      //   Product.find({id: results[r].productId}).then(function (info) {
      //     productInfo.push(info);
      //     i++;
      //     if (i == results.length) {
      //       console.log(productInfo);
      //       res.send({info: productInfo, cart: results});
      //     }
      //   })
      // }
      for (var i=0; i<results.length; i++) {
        productInfo.push(Product.find({id: results[i].productId}))
      }
      Promise.all(productInfo).then(function (info) {
        console.log(info);
        res.send({info: info, cart: results});
      })
    }).catch(function (err) {
      res.serverError(err);
    })
  },
  //添加订单，传入参数：productId，amount，country，province，city，county，street，phone，name，openId，method：post
  addOrder: function (req, res) {
    var contactInfo = {phone: req.body.phone, name: req.body.name, country: req.body.country, province: req.body.province, city: req.body.city, street: req.body.street, openId: req.session.openId};
    Contact.findOrCreate(contactInfo).then(function (result) {
      return res.send(result);
    }).catch(function (err) {
      res.serverError(err);
    })
  },

  confirmOrder: function (req, res) {
    var orderInfo = {amount: req.body.amount, contact: req.body.contact, quantity: req.body.quantity};
    Order.create(orderInfo).then(function (result) {
      return res.send('ok');
    })
  },

  getAddress: function (req, res) {
    Contact.find({openId: req.session.openId}).then(function (results) {
      res.send({address: results});
    }).catch(function (err) {
      res.serverError(err);
    })
  },



}
